# gozerbot/monitor.py
#
#

""" monitors """

__copyright__ = 'this file is in the public domain'

from gozerbot.generic import rlog
import gozerbot.thr as thr

class Monitor(object):

    """ monitor base class """

    def __init__(self):
        self.outs = []

    def add(self, name, callback, pre):
        """ add a say monitoring callback """
        name = name.lower()
        self.outs.append((name, callback, pre))
        rlog(0, 'monitor', 'added %s (%s)' % (name, str(callback)))

    def unload(self, name):
        """ delete monitor item """
        name = name.lower()
        for i in range(len(self.outs)-1, -1, -1):
            if self.outs[i][0] == name:
                del self.outs[i]

class Saymonitor(Monitor):

    """ monitor bot output (bot.say) """

    def callcb(self, botname, printto, txt, who, how, fromm):
        """ fire saymonitor callbacks """
        for i in self.outs:
            # check if precondition is met
            try:
                doit = i[2](botname, printto, txt, who, how, fromm)
            except:
                doit = 0
            if doit:
                # run monitor callback in its own thread
                rlog(0, 'saymonitor', 'excecuting saymonitor callback %s' \
% i[0])
                thr.start_new_thread(i[1], (botname, printto, txt, who, \
how, fromm))

class Outmonitor(Monitor):

    """ monitor for bot output (bot.send) """

    def callcb(self, botname, txt):
        """ fire outmonitor callbacks """
        for i in self.outs:
            # check if precondition is met
            try:
                doit = i[2](botname, txt)
            except:
                doit = 1
            if doit:
                # run monitor callback in thread
                rlog(0, 'outmonitor', 'excecuting outmonitor callback \
%s' % i[0])
                thr.start_new_thread(i[1], (botname, txt))

class Jabbermonitor(Monitor):

    """ monitor jabber output """

    def check(self, msg):
        """ check if <msg> is waited for """
        fromm = msg.getFrom()
        for teller in range(len(self.l)-1,-1,-1):
            i = self.l[teller]
            if i[0] == fromm:
                msg.ticket = i[2]
                i[1].put_nowait(msg)
                del self.l[teller]
                rlog(1,'wait','got response for %s' % i[0])
                return 1

outmonitor = Outmonitor() # bot's output monitor
saymonitor = Saymonitor() # bot.say monitor
jabbermonitor = Jabbermonitor() # monitor for jabber msg
